package com.bigfans.searchservice.service.impl;

import com.bigfans.framework.redis.JedisConnection;
import com.bigfans.framework.redis.JedisExecuteCallback;
import com.bigfans.framework.redis.JedisExecuteWithoutReturnCallback;
import com.bigfans.framework.redis.JedisTemplate;
import com.bigfans.framework.utils.StringHelper;
import com.bigfans.searchservice.service.HotSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author lichong
 * @create 2018-04-03 下午9:13
 **/
@Service(HotSearchServiceImpl.BEAN_NAME)
public class HotSearchServiceImpl implements HotSearchService {

    public static final String BEAN_NAME = "hotSearchServiceImpl";
    public static final String REDIS_KEY = "hotsearch";

    @Autowired
    private JedisTemplate jedisTemplate;

    public List<String> hotSearch(){
        return jedisTemplate.execute(new JedisExecuteCallback<List<String>>() {
            @Override
            public List<String> runInConnection(JedisConnection conn) {
                Set<String> zrange = conn.zrevrange(REDIS_KEY, 0, 4);
                return new ArrayList<>(zrange);
            }
        });
    }

    public void put(String keyword){
        if(StringHelper.isEmpty(keyword)){
            return;
        }
        jedisTemplate.execute(new JedisExecuteWithoutReturnCallback() {
            @Override
            public void runInConnection(JedisConnection conn) {
                conn.zincrby(REDIS_KEY , 1 , keyword);
            }
        });
    }

}
